import os
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Optional


def get_config_file_path() -> Path:
    path_str_in_env: str = os.getenv('ABC_MONITOR_CONFIG_FILE_PATH', default=None)
    if path_str_in_env is None:
        if len(sys.argv) < 1 + 1:
            raise Exception('specify path by environment or cmd arg')
        path_str_in_cmd_arg: str = sys.argv[1]
        return Path(path_str_in_cmd_arg).absolute()
    else:
        path_in_env: Path = Path(path_str_in_env)
        if not path_in_env.is_absolute():
            raise Exception('config file path in environment should be absolute')
        return path_in_env





def load_config_dict(config_file_path: Path) -> dict[str, str]:
    result = dict[str, str]()
    with open(config_file_path, mode='r', encoding='utf-8') as f:
        for line in f:
            parts: list[str] = line.strip().split(sep=':', maxsplit=2)
            if len(parts) != 2:
                continue
            result[parts[0].strip()] = parts[1].strip()
    return result


def mk_address_str(host: str, port: str) -> str:
    result: str = ''
    result += host
    if port is not None and len(port) > 0:
        result += ':'
        result += port
    return result


def parse_receiver_emails(config_str: str) -> list[str]:
    parts = config_str.split(',')
    result = list[str]()
    for part in parts:
        if part is not None and len(part) > 0:
            result.append(part)
    return result


class DictGetter:

    def __init__(self, under: dict[str, str]):
        self._under = under

    def __getitem__(self, item):
        if item in self._under:
            return self._under[item]
        else:
            return ''


@dataclass
class Config:
    protocol: str = None
    host: str = None
    port: Optional[str] = None
    address: str = None

    sender_smtp_server: str = None
    sender_smtp_user: str = None
    sender_smtp_pass: str = None

    sender_email: str = None
    receiver_emails: list[str] = None

    def _load_items(self, pairs_dict: dict[str, str]):
        pairs = DictGetter(pairs_dict)
        self.protocol = pairs['protocol']
        self.host = pairs['host']
        self.port = pairs['port']
        self.address = mk_address_str(self.host, self.port)
        self.sender_smtp_server = pairs['sender_smtp_server']
        self.sender_smtp_user = pairs['sender_smtp_user']
        self.sender_smtp_pass = pairs['sender_smtp_pass']
        self.sender_email = pairs['sender_email']
        self.receiver_emails = parse_receiver_emails(pairs['receiver_emails'])

    def load(self):
        config_file_path: Path = get_config_file_path()
        config_dict: dict[str, str] = load_config_dict(config_file_path)
        self._load_items(config_dict)

